#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2024/2/1 18:31
# @Author : Yoin
import pymysql
from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)


@app.route('/index', methods=['GET', 'POST'])
def index():
    conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", password="root", charset="utf8", db="db1")
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    sql = "select * from admin"
    cursor.execute(sql)  # 第二个参数必须是列表
    # 2.2获取数据库传来的值
    data_list = cursor.fetchall()  # 返回一个列表，里面每行数据是一个字典 [{},{},{}]
    return render_template("index.html", userList=data_list)


@app.route('/add_user', methods=["GET", "POST"])
def add_user():
    conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", password="root", charset="utf8", db="db1")
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    if request.method == "GET":# 返回自己的页面
        return render_template('add_user.html')
    # post 请求
    username = request.form.get("username")
    password = request.form.get("password")
    mobile = request.form.get("mobile")

    sql = "insert into admin (username, password, mobile) values (%s, %s, %s)"
    cursor.execute(sql, [username, password, mobile])  # 第二个参数必须是列表
    conn.commit()
    cursor.close()
    conn.close()
    return redirect(url_for('index'), code=301) # 重定向某网页


if __name__ == '__main__':
    app.run()
